package top.zhangjianyong.tools.user;

import lombok.extern.slf4j.Slf4j;
import top.zhangjianyong.tools.entity.User;
import top.zhangjianyong.tools.utils.SessionUtil;

import java.util.Objects;

/**
 * @author ： zhangjianyong
 * @date ： 2021/11/1 14:37
 */
@Slf4j
public class UserHolder {

    public static IUser user(Class<? extends IUser> clazz) {
        try {
            return SessionUtil.getForTable(clazz);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static IUser user() {
        try {
            return SessionUtil.getForTable(User.class);
        } catch (Exception e) {
            //log.error(e.getMessage(), e);
            return null;
        }
    }

    public static void user(IUser user) throws Exception {
        SessionUtil.setForTable(user);
    }

    public static Long userId() {
        try {
            return Objects.requireNonNull(SessionUtil.getForTable(User.class)).getId();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Long userId(Class<? extends IUser> clazz) {
        try {
            return Objects.requireNonNull(user(clazz)).getId();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Long userIdDefaultNull() {
        try {
            return userId();
        } catch (Exception e) {
            return null;
        }
    }
}
